package accs.product.license;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import accs.model.AccountChecker;
import accs.product.CryptUtils;

public class License {
	private static License instance=null;
	
	public static void loadInstance() throws Exception {
		if(instance==null) {
			instance=new License();
		}
	}
	
	public static License getInstance() {
		if(instance==null) throw new NullPointerException();
		return instance;
	}
	
	private LicenseKey key;
	private DefaultHttpClient client=new DefaultHttpClient();
	private Date fromDate;
	private Date toDate;
	private String features;
	
	private License() throws Exception {
		key=LicenseKey.generate();
//		parseData(readData());
		fromDate=new Date(0);
		toDate=new Date(Long.MAX_VALUE);
		features="all";
	}
	
	public LicenseKey getKey() {
		return key;
	}
	
	private String readData() throws Exception {
		HttpPost post=new HttpPost("");
		List<NameValuePair> list=new ArrayList<NameValuePair>();
		list.add(new BasicNameValuePair("data",CryptUtils.encrypt(System.currentTimeMillis()+(int)(Math.random()*10000)+"|"+key.toString())));
		post.setEntity(new UrlEncodedFormEntity(list));
		
		HttpEntity ent=client.execute(post).getEntity();
		
		byte[] result=EntityUtils.toByteArray(ent);
		if(result[0]==-17 && result[1]==-69 && result[2]==-65) { //BOM entfernen
			result=Arrays.copyOfRange(result,3,result.length); //System.out.println("License BOM");
		}//System.out.println(new String(result));
		return CryptUtils.decrypt(new String(result));
	}
	
	private void parseData(String data) {
		String[] parts=data.split("\\|");
		
		fromDate=new Date(Long.parseLong(parts[0])*1000);
		toDate=new Date(Long.parseLong(parts[1])*1000);
		features=parts[2].toLowerCase();
	}
	
	public boolean checkPermission(AccountChecker checker) {
		Date now=new Date();
		return now.after(fromDate) && now.before(toDate) && (features.contains("all") || features.contains(checker.getName().toLowerCase()));
	}
	
	public Date getFromDate() {
		return fromDate;
	}
	
	public Date getToDate() {
		return toDate;
	}
	
	public String getFeatures() {
		return features;
	}
	
//	public static void main(String[] args) throws Exception {
//		License l = new License();
//		System.out.println(l.getKey());
//		System.out.println();
//		System.out.println(System.currentTimeMillis());
//		System.out.println(getInstance().readData());
//	}
}